<template>
  <div>
    <el-container>
      <el-aside width="200px" v-show="showLeftSide" class="max-h">
        <device-tree
          ref="deviceTree"
          :nodeTree="deviceNodeTree"
          :handleNodeClick="handleDeviceNodeClick"
          :loadDeviceNodeTree="loadDeviceNodeTree"
        ></device-tree>
      </el-aside>

      <div
        style="display: flex; flex-direction: column; justify-content: center;"
      >
        <el-button
          style="height: 10%;"
          size="mini"
          type="primary "
          icon="el-icon-d-arrow-left"
          @click="showLeftSide = false"
          v-if="showLeftSide"
        ></el-button>
        <el-button
          style="height: 10%;"
          size="mini"
          type="primary "
          icon="el-icon-d-arrow-right"
          @click="showLeftSide = true"
          v-if="!showLeftSide"
        ></el-button>
      </div>

      <el-main>
        <div>
          <ele-page
            @handleReset="handleReset"
            v-loading="loading"
            :formConfig="searchDialog"
            :initForm="initForm"
            ref="eleTable"
            :operateList="operateList"
            :otherParams="searchData"
            @handleOperateEvent="handleOperateEvent"
            :column="column"
            maxHeight="340px"
            :getList="getPageOrderListByPriority"
            uniqueId="getPageOrderListByPriority"
          ></ele-page>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import url from "@/axios/url";
import dayjs from "dayjs";
import {
  rowConfig,
  operateList,
  sendThis,
  searchConfig,
} from "@/views/order/mesProdOrder/components/config";
import {
  getchildren,
  getchildrenbytype,
  // getList,
  rowFreezeOrder,
  rowDetail,
  getProdOrderTypeList,
  getProdOrderStatusList,
  printTemplateInfo,
  orderInfoGetBarcode,
  upOrDownPriority,
  getPageOrderListByPriority,
} from "@/api/order/mesProdOrder";
import deviceTree from "./deviceTree.vue";
import { uniqueKey } from "@/utils/judge.js";
const { minioUrl } = url();
export default {
  name: "priority",
  components: { deviceTree },
  mixins: [searchConfig],
  data() {
    const _this = this;
    return {
      showLeftSide: true,
      searchData: {},
      deviceNodeTree: [],
      operateList,
      loading: false,
      getPageOrderListByPriority,
      // getPageOrderListByPriority,
      // 列表页字段的绑定配置
      column: [
        // {
        //   type: "selection",
        //   fixed: "left"
        // },
        {
          type: "index",
          label: $i18n.t("common.order"),
          width: 60,
          fixed: "left",
        },
        // {
        //   prop: "factoryCode",
        //   label: "工厂编码",
        //   minWidth: 120,
        //   showOverflowTooltip: true,
        // },
        {
          prop: "orderCode",
          label: $i18n.t("mesProdOrder.codeStrategy"),
          width: 180,
          showOverflowTooltip: true,
          fixed: "left",
          // render: (h, { row }) => {
          //   return (
          //     <el-link
          //       on={{
          //         click: () => _this.goworkDetails(row)
          //       }}
          //       type="primary">
          //       {row.orderCode}
          //     </el-link>
          //   )
          // }
        },
        {
          prop: "planCode",
          label: $i18n.t("mesProdOrder.productionOrderCode"),
          width: 180,
          showOverflowTooltip: true,

          // render: (h, { row }) => {
          //   return (
          //     <el-link
          //       on={{
          //         click: () => _this.goDetails(row)
          //       }}
          //       type="primary">
          //       {row.planCode}
          //     </el-link>
          //   )
          // }
        },

        {
          prop: "prodCode",
          label: $i18n.t("mesProdOrder.goodsCode"),
          width: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "prodName",
          label: $i18n.t("mesProdOrder.goodsName"),
          width: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "prodOrderType",
          label: $i18n.t("mesProdOrder.prodOrderType"),
          width: 150,
          showOverflowTooltip: true,
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getProdOrderTypeList();
            return list.data.result;
          },
        },
        // {
        //   prop: "priority",
        //   label: "工单优先级",
        //   minWidth: 120,
        //   showOverflowTooltip: true,
        // },
        {
          prop: "quantity",
          label: $i18n.t("mesProdOrder.planQuantity"),
          width: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "actualQuantity",
          label: $i18n.t("mesProdOrder.actualQuantity"),
          width: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "qualifiedQty",
          label: $i18n.t("mesProdOrder.qualifiedQty"),
          width: 150,
          showOverflowTooltip: true,
        },
        {
          prop: "unqualifiedQty",
          label: $i18n.t("mesProdOrder.unqualifiedQty2"),
          width: 160,
          showOverflowTooltip: true,
        },
        {
          prop: "orderStatus",
          label: $i18n.t("mesProdOrder.orderStatus2"),
          width: 100,
          showOverflowTooltip: true,
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getProdOrderStatusList();
            return list.data.result;
          },
        },
        {
          prop: "planBeginDate",
          label: $i18n.t("mesProdOrder.planBeginDate"),
          width: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "planEndDate",
          label: $i18n.t("mesProdOrder.planEndDate"),
          width: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "actualBeginDate",
          label: $i18n.t("mesProdOrder.actualBeginDate"),
          width: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "actualEndDate",
          label: $i18n.t("mesProdOrder.actualEndDate"),
          width: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "workshopName",
          label: $i18n.t("mesProdOrder.workshopName"),
          width: 100,
        },
        {
          prop: "lineName",
          label: $i18n.t("mesProdOrder.lineName2"),
          width: 100,
          showOverflowTooltip: true,
        },
        // {
        //   prop: 'stationCode',
        //   label: $i18n.t('mesTeam.workCellCode'),
        //   minWidth: 200,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'stationName',
        //   label: $i18n.t('mesTeam.workCellName'),
        //   minWidth: 200,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'equipmentCode',
        //   label: $i18n.t('mesProdOrderPlan.equipmentCode'),
        //   minWidth: 200,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'equipmentName',
        //   label: $i18n.t('mesProdOrderPlan.equipmentName'),
        //   minWidth: 200,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: "orderBarcodeRuleName",
        //   label: "条码生成规则",
        //   minWidth: 200,
        //   showOverflowTooltip: true,
        // },
        // {
        //   prop: "isRunning",
        //   label: "是否正在执行接口",
        //   minWidth: 220,
        //   showOverflowTooltip: true,
        //   optionProp: {
        //     value: "value",
        //     label: "description",
        //   },
        //   option: async (data) => {
        //     const list = await getIsRunningList();
        //     return list.data.result;
        //   },
        // },
        {
          prop: "unit",
          label: $i18n.t("mesProdOrder.measureUnit2"),
          width: 110,
          showOverflowTooltip: true,
        },
        {
          prop: "unitCode",
          label: $i18n.t("mesProdOrder.measureUnitCode"),
          width: 140,
          showOverflowTooltip: true,
        },
        // {
        //   prop: "deliveryDate",
        //   label: "交货期",
        //   minWidth: 140,
        //   showOverflowTooltip: true,
        // },
        // {
        //   prop: "slackTime",
        //   label: "交货期宽裕天数",
        //   minWidth: 130,
        //   showOverflowTooltip: true,
        // },
        // {
        //   prop: "prepositionType",
        //   label: "前置工单类型",
        //   minWidth: 100,
        //   showOverflowTooltip: true,
        //   optionProp: {
        //     value: "value",
        //     label: "description",
        //   },
        //   option: async (data) => {
        //     const list = await getPrepositionTypeList();
        //     return list.data.result;
        //   },
        // },
        // {
        //   prop: "prepositionCode",
        //   label: "前置工单号",
        //   minWidth: 150,
        //   showOverflowTooltip: true,
        // },
        {
          prop: "technologyCode",
          label: $i18n.t("mesProdOrder.technologyCode"),
          width: 150,
          showOverflowTooltip: true,
        },
        {
          prop: "technologyName",
          label: $i18n.t("mesProdOrder.technologyName"),
          width: 150,
          showOverflowTooltip: true,
        },
        {
          prop: "versionNumber",
          label: $i18n.t("mesProdOrder.versionNumber2"),
          width: 180,
          showOverflowTooltip: true,
        },

        {
          prop: "createTime",
          label: $i18n.t("common.createTime"),
          width: 160,
          showOverflowTooltip: true,
        },
        {
          prop: "updateTime",
          label: $i18n.t("common.updateTime"),
          width: 160,
          showOverflowTooltip: true,
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"),
          width: 200,
          fixed: "right",
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowBntNumber={2}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              />
            );
          },
        },
      ],
      chooseParam: {
        workshopCode: "",
        workshopName: "",
        lineCode: "",
        lineName: "",
        stationCode: "",
        stationName: "",
      },
      initForm: { planBeginDate: dayjs().format("YYYY-MM-DD") },
    };
  },
  computed: {},
  mounted() {
    sendThis(this);
  },
  created() {
    this.getchildrenbytype();
    // this.searchData.planBeginDate = new Date(Date.parse("yyyy-MM-dd"));
  },
  methods: {
    handleReset() {
      // this.$nextTick(() => { this.$set(this.initForm, 'planBeginDate', new Date())
      // this.$set(this.initForm, 'planBeginDate', this.dayjs())
      //   setTimeout(() => {
      //     this.$set(this.initForm, 'planBeginDate', this.dayjs())
      //     console.log(222, this.searchData.this.dayjs())
      //   }, 3000);
      // })
    },
    dayjs() {
      return dayjs().format("YYYY-MM-DD");
    },

    // 表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name;
      const { codeStrategy } = this.formDataDialog;
      const fnc = {
        add: () => {
          this.disableFields(false);
          this.formDataDialog = {
            simulatedType: "1",
            backflushType: "0",
            codeStrategy: codeStrategy,
          };
          this.visible = true;
        },
        deleteBatch: () => {
          this.$confirm(
            $i18n.t("common.deleteBatch", {
              name: $i18n.t("mesProdOrder.name2"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            const ids = data.rows.map((val) => val.id).join(",");
            this.rowDel(ids);
          });
        },
        // close: () => {
        //   this.$confirm("此操作将强制结束生产工单, 是否继续?", "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   }).then(() => {
        //     const ids = data.rows.map((val) => val.id).join(",");
        //     this.close(ids);
        //   });
        // },
        exportExcel: () => {
          // window.open(
          //   "http://9000.gr817115.m6tfe15g.ceb51d.grapps.cn/file-template/生产工单模板.xls"
          // );

          var url = `${minioUrl}/mes-template/生产工单模板.xls`;
          // console.log("aaaaaaa=", url);
          window.open(url);
        },
        generate: () => {
          if (data.rows.length > 1) {
            let list1 = uniqueKey(data.rows, "prodCode");
            let list2 = uniqueKey(data.rows, "seriesCode");
            let list3 = uniqueKey(data.rows, "stationCode");
            let list4 = uniqueKey(data.rows, "equipmentCode");
            let list5 = uniqueKey(data.rows, "lineCode");
            let list6 = uniqueKey(data.rows, "workshopCode");
            let list7 = uniqueKey(data.rows, "technologyId");
            if (list1.length > 1) {
              this.$message.warning($i18n.t("mesProdOrder.issueLimit2"));
              return;
            }
            if (list2.length > 1) {
              this.$message.warning($i18n.t("mesProdOrder.issueLimit3"));
              return;
            }
            if (list3.length > 1) {
              this.$message.warning($i18n.t("mesProdOrder.issueLimit4"));
              return;
            }
            if (list4.length > 1) {
              this.$message.warning($i18n.t("mesProdOrder.issueLimit5"));
              return;
            }
            if (list5.length > 1) {
              this.$message.warning($i18n.t("mesProdOrder.issueLimit6"));
              return;
            }
            if (list6.length > 1) {
              this.$message.warning($i18n.t("mesProdOrder.issueLimit7"));
              return;
            }
            if (list7.length > 1) {
              this.$message.warning($i18n.t("mesProdOrder.issueLimit8"));
              return;
            }
          }
          const ids = data.rows.map((val) => val.id).join(",");
          this.generateIds = ids;
          if (ids != "") {
            const statusFlag = data.rows.some((val) => val.orderStatus != "0");
            if (statusFlag) {
              this.$message.error($i18n.t("mesProdOrder.issueLimit1"));
            } else {
              this.disableFields_generate(false);
              this.formDescDialog_generate.ids = ids; //将IDs传给弹出框
              this.multipleSelection = data.rows;
              this.time = new Date().getTime();
              this.formDataDialog = {
                ...this.multipleSelection[0],
                // "workshopCode":''
              };
              this.$nextTick(() => {
                this.visible_generate = true;
              });
            }
            // 获取报工类型报工方式
            if (
              data.rows[0].workshopCode != null &&
              data.rows[0].workshopCode != "" &&
              data.rows[0].workshopCode != undefined
            ) {
              this.getModelSetting(data.rows[0].workshopCode);
            }

            console.log("点击下发输出：", data.rows);
          } else {
            this.$message.error($i18n.t("common.multiple"));
          }
        },
        handlePrint: () => {
          const ids = data.rows.map((val) => val.id).join(",");
          this.generateIds = ids;
          if (ids == "") {
            this.$message.error($i18n.t("common.multiple"));
            return false;
          }
          this.loading1 = true;
          // 获取二维码信息
          orderInfoGetBarcode(ids)
            .then((res3) => {
              console.log("1");
              const id = "1567326884034633730";
              // 获取二维码信息
              const res4 = res3.data.result;
              res4.forEach((r) => {
                this.$set(r, "orderCode", r.orderCode);
                this.$set(r, "prodCode", r.prodCode);
                this.$set(r, "quantity", r.quantity);
                if (r.deliveryDate !== "" && r.deliveryDate !== null) {
                  this.$set(r, "deliveryDate", r.deliveryDate);
                } else {
                  this.$set(r, "deliveryDate", "");
                }
              });

              printTemplateInfo(id)
                .then((res2) => {
                  this.barcodeInfo = { ...res2.data.result };

                  localStorage.splitPrint = JSON.stringify({
                    ...this.barcodeInfo,
                    values: res4,
                  });
                  window.open("/momcommon/splitPrint");
                })
                .catch((err) => {
                  console.log(err);
                })
                .finally(() => {
                  this.loading1 = false;
                });
            })
            .finally(() => {
              this.loading1 = false;
            });
        },
        reportOrder: () => {
          this.disableFields_report(false);
          this.reportDetail(data.rows[0].id);
          this.visible_report = true;
        },
        priorityOrder: () => {
          this.showPriorityDialog = true;
        },
      };
      fnc[data.handleName]();
    },
    rowDetail(id) {
      rowDetail(id).then((res) => {
        this.formDataDialog = res.data.result;
      });
    },
    reportDetail(id) {
      rowDetail(id).then((res) => {
        this.formDataDialog = res.data.result;
      });
    },
    // 刷新表格数据
    refresh(isReset = true) {
      console.log("刷新表格数据", this.$refs);
      this.$refs.eleTable.refresh(isReset);
    },
    // 表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        edit: () => {
          this.disableFields(false);
          this.rowDetail(row.id);
          this.visible = true;
        },
        detail: () => {
          this.disableFields(true);
          this.rowDetail(row.id);
          this.visible = true;
        },
        delete: () => {
          this.$confirm(
            $i18n.t("common.deleteSingle", {
              name: $i18n.t("mesProdOrder.name2"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            this.rowDel(row.id);
          });
        },
        close: () => {
          if (row.orderStatus == "4") {
            //工单已完结，不允许冻结
            this.$message.error($i18n.t("mesProdOrder.msg1"));
            return false;
          }
          var confirmmmsg = $i18n.t("mesProdOrder.msg2");
          var successmsg = $i18n.t("mesProdOrder.msg3");
          if (row.orderStatus == "5") {
            confirmmmsg = $i18n.t("mesProdOrder.msg4");
            successmsg = $i18n.t("mesProdOrder.msg5");
          }
          this.$confirm(confirmmmsg, $i18n.t("common.tip"), {
            confirmButtonText: $i18n.t("common.ok"),
            cancelButtonText: $i18n.t("common.cancel"),
            type: "warning",
          }).then(() => {
            this.loading = true;
            rowFreezeOrder({
              orderStatus: row.orderStatus,
              id: row.id,
              prodCode: row.prodCode,
              orderCode: row.orderCode,
            })
              .then((res) => {
                this.$message.success(successmsg);
                this.refresh(false);
              })
              .finally(() => {
                this.loading = false;
              });
            // this.formDataDialog.orderStatus = "5"
          });
        },
        abnormalClosure: () => {
          this.$confirm(
            $i18n.t("mesProdOrder.closeTip"),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            this.rowAbClose(row.id);
          });
        },
        upType: () => {
          this.upOrDownPriority(row.id, "up", row.planBeginDate);
        },
        downTpe: () => {
          this.upOrDownPriority(row.id, "down", row.planBeginDate);
        },
      };
      fnc[handleName]();
    },
    handleDeviceNodeClick(data, node) {
      this.searchData.workshopCode = "";
      this.searchData.workshopName = "";
      this.searchData.lineCode = "";
      this.searchData.lineName = "";
      this.searchData.stationCode = "";
      this.searchData.stationName = "";

      console.log("选择组织结果树：：：：", data, node);
      if (data) {
        // 选择车间
        if (data.level == "4") {
          this.searchData.workshopCode = data.modelingCode;
          this.searchData.workshopName = data.modelingName;
        }

        // 选择线体
        if (data.level == "5") {
          this.searchData.lineCode = data.modelingCode;
          this.searchData.lineName = data.modelingName;
          if (node) {
            this.searchData.workshopCode = node.parent.modelingCode;
            this.searchData.workshopName = node.parent.modelingName;
          }
        }

        // 选择工位
        if (data.level == "6") {
          this.searchData.stationCode = data.modelingCode;
          this.searchData.stationName = data.modelingName;
          if (node && node.parent) {
            this.searchData.lineCode = node.parent.data.modelingCode;
            this.searchData.lineName = node.parent.data.modelingName;
            if (node.parent.parent) {
              this.searchData.workshopCode =
                node.parent.parent.data.modelingCode;
              this.searchData.workshopName =
                node.parent.parent.data.modelingName;
            }
          }
        }
      }
      // 获取接口查询

      this.refresh();
    },
    // 获取车间列表
    getchildrenbytype() {
      getchildrenbytype({
        modelingCode: this.$store.getters.factoryCode,
        level: 4,
        modelingType: 0,
      }).then((response) => {
        if (response.data.code == "0") {
          const deviceNodeTree = response.data.result;
          deviceNodeTree.forEach((d) => (d.label = d.modelingName));
          this.deviceNodeTree = deviceNodeTree;
        }
      });
    },
    // 懒加载设备树
    loadDeviceNodeTree(node, resolve) {
      let level = parseInt(node.data.level) + parseInt(1);
      if (!level) {
        level = "4";
      }
      getchildren({
        modelingCode: node.data.modelingCode,
        level: level,
      }).then((response) => {
        if (response.data.code == "0") {
          const dev = response.data.result;
          dev.forEach((d) => (d.label = d.modelingName));
          resolve(dev);
        }
      });
    },

    // 根据优先级展示工单列表
    // getPageOrderListByPriority() {
    //   let params = this.searchDialog;
    //   // params.planBeginDate = this.searchDialog.planBeginDate;
    //   getPageOrderListByPriority(params).then(rep => {
    //     console.log("根据优先级展示工单列表", rep)
    //   });

    // },

    // 上移或下移行优先级
    upOrDownPriority(id, type, planBeginDate) {
      let params = this.searchData;
      params.planBeginDate = planBeginDate;
      params.type = type;
      params.id = id;
      params.findId = id;
      upOrDownPriority(params).then((rep) => {
        console.log("上移或下移行优先级", rep);
        this.refresh(false);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.max-h {
  max-height: 490px;
  overflow: hidden;
}
</style>
